package server

import (
	"encoding/base64"
	"strings"
	"tcp_server/common"
	. "tcp_server/conf"
	. "tcp_server/protocol"
	"tcp_server/service"
)

// 解析信息并设置sessionKey
func setSessionKey(msg *Message, conn *ClientConn) bool {
	// 使用私钥解密
	data, err := common.RsaDecrypt(msg.Data, Config.PublicKey, Config.PrivateKey)
	if err != nil {
		conn.LogError("private key decrypt failed", err)
		return false
	}

	if len(data) == common.AES_SIZE {
		// 保存会话密钥
		conn.SessionKey = data
		conn.LogConn("get sessionKey:", data)
		return true
	}
	return false
}

// 认证处理
func authUser(msg *Message, conn *ClientConn) bool {
	if conn.SessionKey == "" {
		return false
	}
	//encrptByte, _ := hex.DecodeString(msg.Data)
	// base64节省空间
	encrptByte, err := base64.StdEncoding.DecodeString(msg.Data)
	if err != nil {
		conn.LogError("base64 decrypt failed:", msg.Data)
	}

	// Aes解密
	data, err := common.AesDecrypt(encrptByte, []byte(conn.SessionKey))
	if err != nil {
		conn.LogError("sessionKey decrypt failed:", msg.Data, conn.SessionKey)
		return false
	}

	// 获取用户名和口令并验证用户
	userInfo := strings.Split(string(data), "&")
	if len(userInfo) >= 2 {
		if service.AuthUser(userInfo[0], userInfo[1]) {
			conn.UserId = userInfo[0]
			conn.Authenticated = true
			return true
		}
	}
	conn.LogConn("user auth failed", string(data))
	return false
}
